import router from 'umi/router';
import { message } from 'antd';
import { getList, add, update, deleteOptimal } from './services';

export default {
  namespace: 'optimal',
  state: {
    loading: false,
    list: [],
    pageSize: 10,
    pageNum: 1,
  },

  effects: {

    *getList({ payload }, { call, put }) {
      try {
        yield put({
          type: 'changeLoading',
          payload: true,
        });
        const res = yield call(getList, payload);
        yield put({
          type: 'save',
          payload: {
            list: res.pageData,
            total: res.total,
            pageNum: res.pageNum,
            pageSize: res.pageSize,
          },
        });
      } catch (e) {
        message.error(e.message);
      } finally {
        yield put({
          type: 'changeLoading',
          payload: false,
        });
      }
    },

    *add({ payload, callback }, { call, put, select }) {
      try {
        yield call(add, payload);
        const total = yield select(state => state.optimal.total);
        const pageSize = yield select(state => state.optimal.pageSize);
        const pageNum = Math.ceil((total + 1) / pageSize);
        callback(pageNum, pageSize);
      } catch (e) {
        message.error(e.message);
      }
    },

    *update({ payload, callback }, { call, put, select }) {
      try {
        yield call(update, payload);
        const pageNum = yield select(state => state.optimal.pageNum);
        const pageSize = yield select(state => state.optimal.pageSize);
        message.info('修改成功',1);
        callback(pageNum, pageSize);
      } catch (e) {
        message.error(e.message);
      }
    },

    *deleteOptimal({ payload, callback }, { call, put, select }) {
      try {
        yield call(deleteOptimal, payload);
        const pageSize = yield select(state => state.optimal.pageSize);
        const preTotal = yield select(state => state.optimal.total);
        const curPage = yield select(state => state.optimal.pageNum);
        let curTotal = preTotal - payload.ids.length;
        const lastPage = Math.ceil(curTotal / 10);
        let pageNum = Math.min.apply(null, [curPage, lastPage]);
        message.info('操作成功');
        callback(pageNum, pageSize);
      } catch (e) {
        message.error(e.message);
      }
    },
  },

  reducers: {
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },

    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
